<template>
	<div class="auth">
		<div class="navbar-left">
			<div class="form-group input-group-lg">
				<input type="text" v-model="state.username" class="form-control" placeholder="用户名">
			</div>
			<div class="input-group form-group input-group-lg">
				<input type="password" v-model="state.password" class="form-control" placeholder="密码">
			</div>
			<div class="input-group form-group input-group-lg">
				<input type="text" v-model="state.verifyCode" class="form-control" placeholder="验证码">
				<div class="input-group-addon" @click="initCaptcha">
					<span v-html="state.code"></span>
				</div>
			</div>
			<!-- <div class="input-group form-group input-group-lg">
				 <label style="font-weight: normal;">
					 <input type="checkbox" v-model="remmenber">   记住密码
				 </label>
			</div> -->
			<button type="button" class="btn btn-success btn-lg submit-btn" @click="submit">登录</button>
		</div>
	</div>
</template>
<script setup>
	import {
		ref,
		reactive,
		onBeforeMount
	} from 'vue'

	import {
		useRouter,
		useRoute
	} from 'vue-router'

	import {
		LoginUser,
	} from '../../api/user.js'


	import {
		GetCaptcha
	} from '../../api/common.js'
	import {
		useUserStore
	} from '../../store/user.js'

	const router = useRouter()
	const route = useRoute()
	const userStore = useUserStore()

	onBeforeMount(() => {
		initCaptcha();
	})
	const state = reactive({
		username: ref(''),
		password: ref(''),
		verifyCode: ref(''),
		code: ref('')
	})
	const initCaptcha = () => {
		GetCaptcha().then(({
			code,
			msg,
			data
		}) => {
			if (code == 200) {
				state.code = data.svg
			}
		}).catch(err => {
			console.log('err', err)
		})
	}
	const submit = () => {
		LoginUser({
				username: state.username,
				password: state.password,
				verifyCode: state.verifyCode
			})
			.then(({
				code,
				data,
				msg
			}) => {
				if (code == 200) {
					userStore.setUserInfo(data.user)
					userStore.setToken(data.token);
					if (route.query && route.query.redirect != undefined) {
						const redirect = route.query.redirect;
						router.push(redirect)
					} else {
						router.push('/')
					}
				}
			})
	}
</script>
